import { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
    NavBar,
    Form,
    Button,
    Toast,
    Dialog,
    Picker,
    Popup,
    CheckList,
    Tag,
} from 'antd-mobile';
import { LeftOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import styles from './index.module.less';

interface Examination {
    id: string;
    name: string;
    type: 'lab' | 'imaging' | 'other';
    department: string;
    notes: string;
    isExternal: boolean;
}

const Examination: React.FC = () => {
    const { patientId } = useParams<{ patientId: string }>();
    const navigate = useNavigate();
    const [form] = Form.useForm();
    const [examinations, setExaminations] = useState<Examination[]>([]);
    const [showExaminationPicker, setShowExaminationPicker] = useState(false);

    // Mock data - replace with API call
    const examinationTemplates = [
        { label: '常规检查', value: 'routine' },
        { label: '生化检查', value: 'biochemical' },
        { label: '影像检查', value: 'imaging' },
    ];

    const handleBack = () => {
        Dialog.confirm({
            content: '确定要离开吗？未保存的信息将会丢失',
            onConfirm: () => {
                navigate(-1);
            },
        });
    };

    const handleTemplateSelect = (value: string) => {
        // TODO: Load template content
        console.log('Selected template:', value);
    };

    const handleAddExamination = () => {
        setShowExaminationPicker(true);
    };

    const handleExaminationSelect = (values: string[]) => {
        const newExamination: Examination = {
            id: Date.now().toString(),
            name: values[0],
            type: 'lab',
            department: '检验科',
            notes: '',
            isExternal: false,
        };
        setExaminations([...examinations, newExamination]);
        setShowExaminationPicker(false);
    };

    const handleExaminationChange = (id: string, field: keyof Examination, value: any) => {
        setExaminations(examinations.map(examination =>
            examination.id === id ? { ...examination, [field]: value } : examination
        ));
    };

    const handleRemoveExamination = (id: string) => {
        setExaminations(examinations.filter(examination => examination.id !== id));
    };

    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();
            console.log('Form values:', values);
            // TODO: Submit to backend
            Toast.show({
                icon: 'success',
                content: '保存成功',
            });
            navigate('/');
        } catch (error) {
            console.error('Form validation failed:', error);
        }
    };

    return (
        <div className={styles.container}>
            <NavBar onBack={handleBack} className={styles.navBar}>
                检查申请
            </NavBar>

            <div className={styles.content}>
                <Form
                    form={form}
                    layout="vertical"
                    className={styles.form}
                    footer={
                        <Button
                            block
                            type="submit"
                            color="primary"
                            size="large"
                            onClick={handleSubmit}
                        >
                            完成就诊
                        </Button>
                    }
                >
                    <Form.Item label="检查模板">
                        <Picker
                            columns={[examinationTemplates]}
                            onChange={handleTemplateSelect}
                        >
                            {(items, { open }) => (
                                <div className={styles.templatePicker} onClick={open}>
                                    <span>选择模板</span>
                                    <span className={styles.arrow}>▼</span>
                                </div>
                            )}
                        </Picker>
                    </Form.Item>

                    <Form.Item
                        name="examinations"
                        label="检查项目"
                        rules={[{ required: true, message: '请添加检查项目' }]}
                    >
                        <div className={styles.examinationList}>
                            {examinations.map((examination) => (
                                <div key={examination.id} className={styles.examinationItem}>
                                    <div className={styles.examinationHeader}>
                                        <span className={styles.examinationName}>{examination.name}</span>
                                        <Button
                                            className={styles.removeBtn}
                                            onClick={() => handleRemoveExamination(examination.id)}
                                            icon={<DeleteOutlined />}
                                        />
                                    </div>
                                    <div className={styles.examinationInfo}>
                                        <Tag color="primary">{examination.department}</Tag>
                                        {examination.isExternal && (
                                            <Tag color="warning">外送</Tag>
                                        )}
                                    </div>
                                    <CheckList
                                        className={styles.externalCheck}
                                        value={examination.isExternal ? ['external'] : []}
                                        onChange={(value) => handleExaminationChange(
                                            examination.id,
                                            'isExternal',
                                            value.includes('external')
                                        )}
                                    >
                                        <CheckList.Item value="external">
                                            外送检查
                                        </CheckList.Item>
                                    </CheckList>
                                </div>
                            ))}
                            <Button
                                className={styles.addExaminationBtn}
                                onClick={handleAddExamination}
                                icon={<PlusOutlined />}
                            >
                                添加检查
                            </Button>
                        </div>
                    </Form.Item>
                </Form>
            </div>

            <Popup
                visible={showExaminationPicker}
                onMaskClick={() => setShowExaminationPicker(false)}
                position="bottom"
            >
                <Picker
                    columns={[['血常规', '尿常规', '心电图', 'X光片']]}
                    onConfirm={handleExaminationSelect}
                    onCancel={() => setShowExaminationPicker(false)}
                />
            </Popup>
        </div>
    );
};

export default Examination; 